package com.gc.ordersys2.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gc.ordersys2.common.result.Result;
import com.gc.ordersys2.common.result.ResultUtils;
import com.gc.ordersys2.common.utils.EmptyUtils;
import com.gc.ordersys2.entity.Cart;
import com.gc.ordersys2.entity.Type;
import com.gc.ordersys2.service.ICartService;
import com.gc.ordersys2.service.ITypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author cuijianhao
 * @since 2024-09-05
 */
@RestController
@RequestMapping("/cart")
public class CartController {

    @Autowired
    ICartService service;

    @RequestMapping("/getList")
    public Object getList(Cart cart){
        //调用service层的自定义方法
        List<Cart> list = service.getList(cart);
        //返回结果
        return ResultUtils.returnDataSuccess(list);
    }

    @RequestMapping("/add")
    public Object add(Cart cart) {
        //先判断是否已经存在，若无则新增，若有则更新数量
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("pro_id", cart.getProId());
        queryWrapper.eq("desk_id", cart.getDeskId());
        Cart one = service.getOne(queryWrapper);
        if (EmptyUtils.isNotEmpty(one)) {
            one.setNum(one.getNum() + cart.getNum());
            if(one.getNum()==0){
                if (service.removeById(one)) {
                    return ResultUtils.returnSuccess();
                } else
                    return ResultUtils.returnFail("加购失败");
            }else {
                if (service.updateById(one)) {
                    return ResultUtils.returnSuccess();
                } else
                    return ResultUtils.returnFail("加购失败");
            }
        } else {
            if (service.save(cart)) {
                return ResultUtils.returnSuccess();
            } else {
                return ResultUtils.returnFail("添加失败");
            }
        }
    }

    @RequestMapping("/del")
    public Object del(Integer deskId){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("desk_id",deskId);
        if(service.remove(queryWrapper)){
            return ResultUtils.returnSuccess();
        }else{
            return ResultUtils.returnFail("删除失败");
        }
    }
}